<?php

/**
 * HomeAPIController: tbd
 * */

class HomeAPIController extends SimpleRestController {

    # the parent controller class went through the trouble of calling the specific method,
    # but most of our logic is in common between these, so we just call execute().
    public function get()    { $this->execute(); }
    public function post()   { $this->execute(); }
    public function put()    { $this->execute(); }
    public function delete() { $this->execute(); }

    #$this->request['resource']    = $resource ? $resource : 'home';
    #$this->request['method']      = strtolower($_SERVER['REQUEST_METHOD']);
    #$this->request['script_name'] = $_SERVER['SCRIPT_NAME'];
    #$this->request['server_name'] = $_SERVER['SERVER_NAME'];
    #$this->request['server']      = 'http://' . $_SERVER['SERVER_NAME'];
    #$this->request['headers']     = $this->getHeaders();
    #$this->request['format']      = isset($_GET['format']) ? trim($_GET['format']) : null;
    #$this->request['params']      = $_GET; (for GET method)

    #  * App\MustacheTemplateVars Object
    #  * (
    #  *     [template_name] => test
    #  *     [layout] => default
    #  *     [user_token] => guest
    #  *     [user] => Array
    #  *         (
    #  *             [user_id] => 1
    #  *             [email] =>
    #  *             [username] => guest
    #  *             [cell_phone] =>
    #  *             [salt] => xxxxxx
    #  *             [algorithm] => xxxxxx
    #  *             [algorithm_option] =>
    #  *             [lang] =>
    #  *             [locale] =>
    #  *             [timezone] =>
    #  *             [theme] =>
    #  *             [nick_name] =>
    #  *             [first_name] =>
    #  *             [middle_name] =>
    #  *             [last_name] =>
    #  *             [address1] =>
    #  *             [city] =>
    #  *             [state_code] =>
    #  *             [postal_code] =>
    #  *             [country_code] =>
    #  *             [last_login_dttm] =>
    #  *             [default_group_id] => 1
    #  *             [default_app_id] => 1
    #  *             [user_token] => guest
    #  *             [group_id] => 1
    #  *             [group_name] => all-users
    #  *             [app_id] => 1
    #  *         )
    #  *     [groups] => Array
    #  *         (
    #  *             [0] => Array
    #  *                 (
    #  *                     [group_id] => 1
    #  *                     [group_name] => all-users
    #  *                     [group_long_name] => All Users
    #  *                     [owner_user_id] => 1
    #  *                     [public_ind] => Y
    #  *                 )
    #  *         )
    #  *     [apps] => Array
    #  *         (
    #  *             [0] => Array
    #  *                 (
    #  *                     [app_id] => 1
    #  *                     [app_cd] => dbfront
    #  *                     [app_name] => Database Workbench
    #  *                     [public_ind] => Y
    #  *                 )
    #  *         )
    #  *     [perms] => Array
    #  *         (
    #  *             [/] => 1
    #  *             [/api] => 1
    #  *             [/app] => 1
    #  *         )
    #  *     [logged_in] =>
    #  *     [options] => Array
    #  *         (
    #  *             [app.title] => DBFoundry
    #  *             [theme] => default
    #  *             [locale] => en
    #  *             [timezone] => America/New_York
    #  *             [apps_urldir] => https://www.dbfoundry.com/v/dev/apps
    #  *             [ext_urldir] => https://www.dbfoundry.com/v/dev/apps/ext-4.1.1a
    #  *             [ext_jsfile] => ext-all.js
    #  *             [test_mode] => 1
    #  *             [signup_mode] => link
    #  *             [online_mode] => amember
    #  *             [site_baseurl] => https://www.dbfoundry.com
    #  *             [members_root_urldir] => /v/dev/members
    #  *             [website_root_urldir] => /v/dev
    #  *             [desktop_root_urldir] => /v/dev/workbench
    #  *             [mobile_root_urldir] => /v/dev/mobile
    #  *             [workbench_root_urldir] => /v/dev/workbench
    #  *         )
    #  *     [connection] => Array
    #  *         (
    #  *             [client_connection_token] => 8b62e0a19eda076dd3dadfe57d5e76ddad3e92d4f0d0c19e99c9f1809ef52a3f
    #  *         )
    #  *     [session] => Array
    #  *         (
    #  *             [user_token] => guest
    #  *             [auth_token] => xxxxxx
    #  *             [session_expire_dttm] => 2038-01-01 00:00:00
    #  *             [group_id] => 1
    #  *             [app_id] => 1
    #  *         )
    #  *     [site_dir] => /mnt/id/apache/dbfoundry.com/env/dev/data/fs/pub/web/public-site
    #  *     [pages_dir] => /mnt/id/apache/dbfoundry.com/env/dev/data/fs/pub/web/public-site/pages
    #  *     [partials_dir] => /mnt/id/apache/dbfoundry.com/env/dev/data/fs/pub/web/public-site/partial-pages
    #  *     [resources_dir] => /mnt/id/apache/dbfoundry.com/env/dev/data/fs/pub/web/public-site/page-resources
    #  * )

    private function execute() {
        global $context, $options, $trace;
        if ($trace) trace_entry();

        $http_method = $this->request['method'];
        $resource    = $this->request['resource'];
        $request     = isset($this->request['params']) ? $this->request['params'] : array();
        if (($http_method === 'post' || (isset($options['test_mode']) && $options['test_mode'])) && isset($request['op'])) {
            $http_method = $request['op'];
        }
        $response    = array();

        $resource_parts = explode('/', $resource);
        if (count($resource_parts) == 0 || strlen($resource_parts[0]) < 6) { # 6 chars is the minimum length for a username/group_name
            $this->responseStatus = 403;
            $this->responseBody = "Forbidden: Group Name Not Specified";
        }
        else {
            debug_print("HomeAPIController.execute()...");

            $url_group_name        = $resource_parts[0];
            array_shift($resource_parts);

            $url_group_id          = $context->getOwnerId($url_group_name);
            $group_owner_dir       = $context->getOwnerDir(null, $url_group_id);
            $user                  = $context->getAuthenticatedUser();
            $group_name            = isset($user['group_name']) ? $user['group_name'] : APP_ALLUSERS_GROUP_NAME;

            if ($group_name === $url_group_name) {
                $is_member         = true;
            }
            else {
                $group_defs        = $context->getAuthorizedGroups();
                $is_member         = false;
                foreach ($group_defs as $group_def) {
                    if ($group_def['group_name'] === $url_group_name) {
                        $is_member = true;
                        break;
                    }
                }
            }

            $web_dir           = "$group_owner_dir/web";
            $site_dir          = $is_member ? "$web_dir/member-site" : "$web_dir/public-site";

            $owner_relfile = (count($resource_parts) == 0) ? 'home' : implode('/', $resource_parts);
            if (!$owner_relfile) $owner_relfile = 'home';
            if (is_dir("$site_dir/pages/$owner_relfile")) $owner_relfile .= '/home';

            if (preg_match('/^(.+)\.([^.]+)$/', $owner_relfile, $matches)) {
                $template_name = $matches[1];
                $file_ext      = $matches[2];
            }
            else {
                $template_name = $owner_relfile;
                $file_ext      = 'html';
            }

            $layout_dir           = "$site_dir/layouts";
            $pages_dir            = "$site_dir/pages";
            $partials_dir         = "$site_dir/partial-pages";
            $resources_dir        = "$site_dir/page-resources";
            debug_print("HomeAPIController.execute(): file=$site_dir/pages/$template_name.$file_ext]");

            if (!isset($url_group_id) || !$url_group_id) {
                $this->responseStatus = 404;
                $this->responseContentType = 'text/html';
                $this->responseBody = <<<EOF
<!doctype html>
<html>
<head>
  <title>File, Resource, or Web Page Not Found</title>
</head>
<body>
File, Resource, or Web Page at [$resource] Not Found
</body>
</html>
EOF;
            }
            elseif ($file_ext === 'html' && is_file("$site_dir/pages/$template_name.$file_ext")) {

                $template_vars = new \App\MustacheTemplateVars(array(
                    'url_group_name' => $url_group_name,
                    'localsite_root_urldir' => $options['website_root_urldir']."/home/$url_group_name",
                    'template_name' => $template_name,
                    'site_dir' => $site_dir,
                    'pages_dir' => $pages_dir,
                    'partials_dir' => $partials_dir,
                    'resources_dir' => $resources_dir
                ));
                $layout = $template_vars->layout;

                $cache_dir     = $group_owner_dir.'/temp/cache/templates';
                if (! is_dir($cache_dir)) $context->mkdir($cache_dir);

                $layout_loader   = new Mustache_Loader_FilesystemLoader($layout_dir, array('extension'=>''));
                $page_loader     = new Mustache_Loader_FilesystemLoader($pages_dir, array('extension'=>'html'));
                $partials_loader = new Mustache_Loader_FilesystemLoader($partials_dir, array('extension'=>''));
                $logger          = new Mustache_Logger_StreamLogger('php://stderr');

                $layout_template_engine = new Mustache_Engine(array(
                    'cache' => $cache_dir,
                    'loader' => $layout_loader,
                    'partials_loader' => $partials_loader,
                    'logger' => $logger
                ));
                $layout_begin = '';
                $layout_end   = '';
                if (is_file("$layout_dir/$layout.begin")) $layout_begin = $layout_template_engine->loadTemplate("$layout.begin")->render($template_vars);
                if (is_file("$layout_dir/$layout.end"))   $layout_end   = $layout_template_engine->loadTemplate("$layout.end")->render($template_vars);

                $template_engine = new Mustache_Engine(array(
                    'cache' => $cache_dir,
                    'loader' => $page_loader,
                    'partials_loader' => $partials_loader,
                    'logger' => $logger
                ));
                $page_body = $template_engine->loadTemplate($template_name)->render($template_vars);

                $this->responseBody = $layout_begin . $page_body . $layout_end;
                $this->responseStatus = 200;
                $this->responseContentType = 'text/html';
            }
            elseif (is_file("$site_dir/pages/$owner_relfile")) {   # FILES THAT ARE IN THE PAGES DIRECTORY
                $this->responseStatus = 200;
                $this->responseFilename = "$site_dir/pages/$owner_relfile";
            }
            elseif (count($resource_parts) > 0 && $resource_parts[0] === 'resources') {   # FILES THAT MAY BE IN A SITE RESOURCE DIR OR THE GLOBAL RESOURCE DIR
                array_shift($resource_parts);
                $resource_relfile = implode('/', $resource_parts);
                if ($is_member && is_file("$site_dir/page-resources/$resource_relfile")) {  # FILES THAT CAN BE DOWNLOADED
                    $this->responseStatus = 200;
                    $this->responseFilename = "$site_dir/page-resources/$resource_relfile";
                }
                elseif (is_file("$web_dir/page-resources/$resource_relfile")) {  # FILES THAT CAN BE DOWNLOADED
                    $this->responseStatus = 200;
                    $this->responseFilename = "$web_dir/page-resources/$resource_relfile";
                }
                else {
                    $this->responseStatus = 404;
                    $this->responseContentType = 'text/html';
                    $this->responseBody = <<<EOF
<!doctype html>
<html>
<head>
  <title>File, Resource, or Web Page Not Found</title>
</head>
<body>
File, Resource, or Web Page at [$resource] Not Found
</body>
</html>
EOF;
                }
            }
            elseif ($is_member) {
                if (is_file("$group_owner_dir/$owner_relfile")) {  # FILES THAT CAN BE DOWNLOADED
                    $this->responseStatus = 200;
                    $this->responseFilename = "$group_owner_dir/$owner_relfile";
                    if (isset($request['download'])) {
                        $this->responseContentType = "application/octet-stream";
                    }
                }
                else {
                    $this->responseStatus = 404;
                    $this->responseContentType = 'text/html';
                    $this->responseBody = <<<EOF
<!doctype html>
<html>
<head>
  <title>File, Resource, or Web Page Not Found</title>
</head>
<body>
File, Resource, or Web Page at [$resource] Not Found
</body>
</html>
EOF;
                }
            }
            else {
                $this->responseStatus = 403;
                $this->responseContentType = 'text/html';
                $this->responseBody = <<<EOF
<!doctype html>
<html>
<head>
  <title>Forbidden: You are not currently logged in to the requested group</title>
</head>
<body>
Forbidden: You are not currently logged in to the requested group [$url_group_name]
</body>
</html>
EOF;
            }
        }

        $this->response = $response;

        #$response['resource'] = $resource;
        #$response['http_method'] = $http_method;

        if ($trace) trace_exit();
    }
}
